package apptoko.com;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Shader.TileMode;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event.BuyFailEvent;
import apptoko.com.event.Event.BuyMultipleContentSuccessEvent;
import apptoko.com.event.Event.BuySuccessEvent;
import apptoko.com.event.Event.CollectionContentSuccessEvent;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.GetMultipleDownloadLinkSucessEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.model.ContentItemInfo;
import apptoko.com.model.DownloadLaterItem;
import apptoko.com.model.DownloadLink;
import apptoko.com.model.GiftSetting;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.ScaleImageView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.androidquery.AQuery;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class CollectionListItemActivity extends SherlockFragmentActivity implements OnItemClickListener{
	
	private int collectionId;
	private EventBus eventBus;
	private BackgroundTasks bgTask;
	private AQuery aq;
	private String accessToken;
	private CollectionItemAdapter adapter;
	private List<ContentItemInfo> list;
	private ListView listView;
	private PackageEventReceiver receiver;
	private ProgressDialog pDialog;
	private ActionMode actionMode;
	private boolean[] checkBoxState;
	private ContentItemInfo selectedItem;
	private DownloadManager downloadManager;
	private int count = 0;
	private DialogInterface.OnClickListener onClick;
	private String countryCode;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_coll_list_item);
		EasyTracker.getInstance().setContext(this);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		countryCode = Utils.getStaticCountryCode(this);
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(receiver, filter);
		downloadManager = new DownloadManager(getContentResolver(), getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle(getIntent().getStringExtra(Constants.COLLECTION_TITLE));
		listView = (ListView) findViewById(R.id.list_collection_item);
		collectionId = getIntent().getIntExtra(Constants.COLLECTION_LIST_ID, -1);
		accessToken = Utils.getStaticAccessToken(this);
		eventBus = EventBus.getDefault();
		bgTask = new BackgroundTasks(this);
		aq = new AQuery(this);
		list = new ArrayList<ContentItemInfo>();
		adapter = new CollectionItemAdapter(CollectionListItemActivity.this, R.layout.collection_content_item, list);
		View layout = getLayoutInflater().inflate(R.layout.collection_list_banner, null);
		ScaleImageView banner = (ScaleImageView) layout.findViewById(R.id.collection_banner);
		AQuery aqBanner = new AQuery(layout);
		aqBanner.id(banner).image(getIntent().getStringExtra(Constants.COLLECTION_COVER), true, true);
		listView.addHeaderView(layout);
		aq.id(listView).adapter(adapter).itemClicked(this).gone();
		aq.id(R.id.coll_item_progress).visible();
		aq.id(R.id.btn_retry_coll_item).gone();
		bgTask.getCollectionContent(accessToken, collectionId, "has_tablet");
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(this, DownloadService.class);
		startService(intent);
	}
	
	public void onEventMainThread(CollectionContentSuccessEvent event){
		checkBoxState = new boolean[event.getItemList().size()*2];
		List<ContentItemInfo> contentList = event.getItemList();
		for(ContentItemInfo item : contentList){
			list.add(item);
		}
		adapter.notifyDataSetChanged();
		aq.id(listView).visible();
		aq.id(R.id.coll_item_progress).gone();
		aq.id(R.id.btn_retry_coll_item).gone();
	}
	
	public void onEventMainThread(RequestFailEvent event){
		ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
		aq.id(R.id.list_collection_item).gone();
		aq.id(R.id.coll_item_progress).gone();
		aq.id(R.id.btn_retry_coll_item).visible().clicked(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				aq.id(R.id.coll_item_progress).visible();
				aq.id(R.id.btn_retry_coll_item).gone();
				bgTask.getCollectionContent(accessToken, collectionId, "has_tablet");
			}
		});
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_collection_list_item, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.menu_download_all:
			showConfirm(new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.DOWNLOAD_ALL_COLLECTION, "Download all collection " + getIntent().getStringExtra(Constants.COLLECTION_TITLE), Long.valueOf(1));
					if(countryCode.equalsIgnoreCase("us")){
						
					} else {
						downloadAll();
					}
				}
			});
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		if(v.getTag() == null){
			return;
		}
		ContentItemInfo item = (ContentItemInfo) parent.getItemAtPosition(pos);
		if(item.getApplicationId().startsWith("market")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(item.getApplicationId())));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
		}else{
			Intent intent = new Intent(CollectionListItemActivity.this, ItemBrokerActivity.class);
			intent.putExtra(Constants.PREVIOUS_SCREEN, "collection");
			intent.putExtra(Constants.SLUG, item.getApplicationId());
			intent.putExtra(Constants.FROM, 3);
			intent.putExtra(Constants.KEY_REFERER, "ads");
			intent.putExtra(Constants.STORE_KEY, "apps");
			startActivity(intent);
		}
		
	}
	
	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				String packageName = "";
				for(ContentItemInfo item : list){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(installedName)){
						item.setInstalled(true);
					}
				}
				adapter.notifyDataSetChanged();
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String packageName = "";
				String uninstalledName = intent.getDataString().split(":")[1];
				for(ContentItemInfo item : list){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(uninstalledName)){
						item.setInstalled(false);
					}
				}
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	@SuppressLint("NewApi")
	private class CollectionItemAdapter extends ArrayAdapter<ContentItemInfo> {
		
		private AQuery aq;
		private Typeface robotoMedium;
		private Typeface robotoCondensed;
		private Typeface robotoBoldCondensed;
		private Resources res;

		public CollectionItemAdapter(Context context, int resource, List<ContentItemInfo> objects) {
			super(context, resource, objects);
			// TODO Auto-generated constructor stub
			res = getResources();
			robotoBoldCondensed = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_bold_condensed));
			robotoCondensed = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_condensed));
			robotoMedium = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_medium));
		}
		
		private int getColor(){
			return res.getColor(R.color.app_indicator);
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.collection_content_item, null);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);
				holder.appName = (TextView) convertView.findViewById(R.id.name);
				holder.author = (TextView) convertView.findViewById(R.id.author);
				holder.rating = (RatingBar) convertView.findViewById(R.id.rating);
				holder.price = (TextView) convertView.findViewById(R.id.price);
				holder.priceUnit = (ImageView) convertView.findViewById(R.id.price_unit);
				holder.checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
				holder.btnQuickMenu = (ImageButton) convertView.findViewById(R.id.btn_quick_menu);
				holder.ribbonGift = (ImageView) convertView.findViewById(R.id.ribbon_gift);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final ContentItemInfo item = getItem(position);
			if (item != null) {
				aq = new AQuery(convertView);
				if(item.getGiftbox() == 1){
					aq.id(holder.ribbonGift).visible();
				} else {
					aq.id(holder.ribbonGift).gone();
				}
				if(UILApplication.getInstance().isLoadAllImgs()){
					aq.id(R.id.icon).visible();
					Bitmap placeholder = aq.getCachedImage(R.drawable.ic_loading);
					if(aq.getCachedFile(item.getAvatar())!=null){
						aq.id(R.id.icon).image(aq.getCachedFile(item.getAvatar()),75);
						Log.e("NMN","get CollectionListItem from CachedFile");
					}else{
						Log.e("NMN","get CollectionListItem from server");
						if(aq.shouldDelay(position, convertView, parent, item.getAvatar())){
			                aq.id(R.id.icon).image(placeholder, AQuery.RATIO_PRESERVE);
			            } else {
			                aq.id(R.id.icon).image(item.getAvatar(), true, true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK, AQuery.RATIO_PRESERVE);
			            }
					}
		            
				}else{
					aq.id(R.id.icon).visibility(View.GONE);
				}
				aq.id(holder.appName).text((position + 1) + ". " + item.getTitle()).typeface(robotoBoldCondensed);
				aq.id(holder.author).text(item.getAuthor()).typeface(robotoCondensed);
				float rate;
				if(item.getTotalRate() > 0){
					rate = item.getSumRate() / item.getTotalRate();
				} else {
					rate = 0;
				}
				aq.id(holder.rating).rating(rate);
					if(item.isInstalled()){
						aq.id(holder.checkBox).invisible().enabled(false);
						aq.id(holder.price).text(res.getString(R.string.installed).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor());
						aq.id(holder.priceUnit).invisible();
							aq.id(holder.btnQuickMenu).visible().clicked(new OnClickListener() {
								@Override
								public void onClick(View v) {
									selectedItem = item;
									if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
										PopupMenu menu = new PopupMenu(CollectionListItemActivity.this, v);
										menu.getMenuInflater().inflate(R.menu.installed_app_menu, menu.getMenu());
										menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
											@Override
											public boolean onMenuItemClick(android.view.MenuItem menuItem) {
												// TODO Auto-generated method stub
												switch (menuItem.getItemId()) {
												case R.id.menu_launch:
													Intent launch = getPackageManager().getLaunchIntentForPackage(item.getPackageName());
													launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
													startActivity(launch);
													break;
												case R.id.menu_uninstall:
													Utils.uninstallAPK(CollectionListItemActivity.this, item.getPackageName());
													break;
												}
												return true;
											}
										});
										menu.show();
									} else {
										main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(CollectionListItemActivity.this);
										popupMenuCompat.add(1, R.string.menu_launch);
										popupMenuCompat.add(2, R.string.menu_uninstall);
										popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
											@Override
											public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
												switch (menuItem.getItemId()) {
												case 1:
													Intent launch = getPackageManager().getLaunchIntentForPackage(item.getPackageName());
													launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
													startActivity(launch);
													break;
												case 2:
													Utils.uninstallAPK(CollectionListItemActivity.this, item.getPackageName());
													break;
												}
											}
										});
										popupMenuCompat.show(v);
									}
								}
							});
					} else {
						aq.id(holder.checkBox).visible().enabled(true).checked(checkBoxState[position]).clicked(new OnClickListener() {
							@Override
							public void onClick(View v) {
								 if(((CheckBox)v).isChecked()){
					                   checkBoxState[position] = true;
					                   item.setChecked(true);
					                   if(null == actionMode){
											actionMode = startActionMode(new DownloadedItemActionMode());
					                   }
					                   count++;
					               } else{
					                   checkBoxState[position] = false;
					                   item.setChecked(false);
					                   count--;
					               }
					               if(count == 0){
					            	   actionMode.finish();
					               }
					               for(int i=0; i < checkBoxState.length; i++){
					            	   System.err.println(checkBoxState[i]);
					               }
							}
						});
							aq.id(holder.btnQuickMenu).visible().clicked(new OnClickListener() {
								@Override
								public void onClick(View v) {
									selectedItem = item;
									if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
										PopupMenu menu = new PopupMenu(CollectionListItemActivity.this, v);
										menu.getMenuInflater().inflate(R.menu.not_installed_app_menu, menu.getMenu());
										menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
											@Override
											public boolean onMenuItemClick(android.view.MenuItem menuItem) {
												// TODO Auto-generated method stub
												switch (menuItem.getItemId()) {
												case R.id.menu_install:
													if(!countryCode.equalsIgnoreCase("vn")){
														Intent gp = new Intent(Intent.ACTION_VIEW);
														gp.setData(Uri.parse(item.getRootLink()));
														startActivity(gp);
													} else {
														if(checkLogin()){
															checkGift();
														} else {
															AlertDialogManager am = new AlertDialogManager(CollectionListItemActivity.this);
															am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
																@Override
																public void onClick(DialogInterface dialog, int which) {
																	// TODO Auto-generated method stub
																	switch (which) {
																	case DialogInterface.BUTTON_POSITIVE:
																		Intent intent = new Intent(CollectionListItemActivity.this, LoginActivity.class);
																		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																		startActivity(intent);
																		break;
																	case DialogInterface.BUTTON_NEGATIVE:
																		dialog.dismiss();
																		break;
																	}
																}
															});
														}
													}
													break;
												case R.id.menu_add_wishlist:
													DatabaseHelper db = new DatabaseHelper(CollectionListItemActivity.this);
													DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
													dlItem.setPrice1(item.getPrice());
													dlItem.setPrice2(item.getPrice2());
													dlItem.setPackageName(item.getPackageName());
													dlItem.setType(Constants.ANDROID_STORE);
													boolean added = db.addDownloadLater(dlItem);
													if(added){
														Toast.makeText(CollectionListItemActivity.this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
													} else {
														Toast.makeText(CollectionListItemActivity.this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
													}
													break;
												}
												return true;
											}
										});
										menu.show();
									} else {
										main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(CollectionListItemActivity.this);
										popupMenuCompat.add(1, R.string.menu_install);
										popupMenuCompat.add(2, R.string.add_to_wishlist);
										popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
											@Override
											public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
												switch (menuItem.getItemId()) {
												case 1:
													if(!countryCode.equalsIgnoreCase("vn")){
														Intent gp = new Intent(Intent.ACTION_VIEW);
														gp.setData(Uri.parse(item.getRootLink()));
														startActivity(gp);
													} else {
														if(checkLogin()){
															checkGift();
														} else {
															AlertDialogManager am = new AlertDialogManager(CollectionListItemActivity.this);
															am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
																@Override
																public void onClick(DialogInterface dialog, int which) {
																	// TODO Auto-generated method stub
																	switch (which) {
																	case DialogInterface.BUTTON_POSITIVE:
																		Intent intent = new Intent(CollectionListItemActivity.this, LoginActivity.class);
																		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																		startActivity(intent);
																		break;
																	case DialogInterface.BUTTON_NEGATIVE:
																		dialog.dismiss();
																		break;
																	}
																}
															});
														}
													}
													break;
												case 2:
													DatabaseHelper db = new DatabaseHelper(CollectionListItemActivity.this);
													DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
													dlItem.setPrice1(item.getPrice());
													dlItem.setPrice2(item.getPrice2());
													dlItem.setPackageName(item.getPackageName());
													dlItem.setType(Constants.ANDROID_STORE);
													boolean added = db.addDownloadLater(dlItem);
													if(added){
														Toast.makeText(CollectionListItemActivity.this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
													} else {
														Toast.makeText(CollectionListItemActivity.this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
													}
													break;
												}
											}
										});
										popupMenuCompat.show(v);
									}
								}
							});
						if (item.getPrice() == 0 && item.getPrice2() == 0) {
							aq.id(holder.price).text(res.getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor());
							aq.id(holder.priceUnit).invisible();
						} else if(item.getPrice() == 0 && item.getPrice2() != 0){
							aq.id(holder.price).text(String.valueOf(item.getPrice2())).typeface(robotoMedium).textColor(res.getColor(R.color.app_indicator));
							aq.id(holder.priceUnit).image(R.drawable.tym_purple).visible();
						} else if(item.getPrice() != 0 && item.getPrice2() == 0){
							aq.id(holder.price).text(String.valueOf(item.getPrice())).typeface(robotoMedium).textColor(res.getColor(R.color.app_indicator));
							aq.id(holder.priceUnit).image(R.drawable.tym_green).visible();
						}
					}
			}
			return convertView;
		}
		
	}
	
	private void download(final ContentItemInfo item){
		AlertDialogManager am = new AlertDialogManager(CollectionListItemActivity.this);
		am.showWebViewDialog(aq, item.getInstallAttachApplication(), CollectionListItemActivity.this, item.getPermission(), R.string.app_permissions, item.getAttachApplicationSlug(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String accessToken = Utils.getStaticAccessToken(CollectionListItemActivity.this);
				pDialog = ProgressDialogManager.showProgressDialog(CollectionListItemActivity.this, R.string.loading);
				bgTask.buyContent("",accessToken, item.getApplicationId(), 0);
				dialog.dismiss();
			}
		});
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(this);
	}
	
	public static class ViewHolder {
		ImageView icon;
		TextView appName;
		TextView author;
		RatingBar rating;
		TextView price;
		ImageView priceUnit;
		ImageButton btnQuickMenu;
		CheckBox checkBox;
		ImageView ribbonGift;
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		String accessToken = Utils.getStaticAccessToken(CollectionListItemActivity.this);
		bgTask.getDownloadLink("",accessToken, event.getSlug(), 0, Utils.getStaticIsRooted(CollectionListItemActivity.this), "direct");
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		AppMsg.makeText(CollectionListItemActivity.this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	private void checkGift(){
		if(selectedItem.getGiftbox() == 1){
			final DatabaseHelper db = new DatabaseHelper(this);
			AlertDialogManager am = new AlertDialogManager(this);
			GiftSetting gift = db.getGiftSync(selectedItem.getApplicationId());
			if(gift != null && gift.getReceived() == 1){
				download(selectedItem);
			} else {
				if(selectedItem.getGiftboxDaysToGet() == 0){
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(0);
					gs.setName(selectedItem.getPackageName());
					gs.setSlug(selectedItem.getApplicationId());
					gs.setAppName(selectedItem.getTitle());
					gs.setPicture(selectedItem.getAvatar());
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							download(selectedItem);
							db.addGift(gs);
						}
					};
					am.showGiftDialog(R.string.gift_message, 0, onClick);
				} else {
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(selectedItem.getGiftboxDaysToGet());
					gs.setName(selectedItem.getPackageName());
					gs.setSlug(selectedItem.getApplicationId());
					gs.setAppName(selectedItem.getTitle());
					gs.setPicture(selectedItem.getAvatar());
					gs.setTimeToReceive(Utils.calculateDaysToGetGift(selectedItem.getGiftboxDaysToGet()));
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							download(selectedItem);
							db.addGift(gs);
						}
					};
					am.showGiftDialog(R.string.gift_message_days, selectedItem.getGiftboxDaysToGet(), onClick);
				}
			}
		} else {
			download(selectedItem);
		}
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(selectedItem.getInstallAttachApplication() == 1){
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.buyAttachedContent(accessToken, selectedItem.getAttachApplicationSlug(), 0);
		}
		DownloadLink download = event.getDl();
		List<String> extraUrls = download.getExtraDownloads();
		if(extraUrls.size() > 0){
			for(String extraUrl : extraUrls){
				Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				if(extraUrl.endsWith("obb")){
					String obbDir = StorageUtils.OBB_ROOT + selectedItem.getPackageName() + "/";
					File obb = new File(obbDir);
					if(!obb.exists()){
						obb.mkdirs();
					}
					request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
				} else {
					request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
				}
				request.setTitle(String.format(getResources().getString(R.string.additional_file), selectedItem.getTitle()));
				request.setDescription(selectedItem.getAvatar());
				setMimeType(request);
				downloadManager.enqueue(request);
			}
		}
		String url = download.getDownload();
		Uri srcUri = Uri.parse(url.replace(" ", "%20"));
		DownloadManager.Request request = new Request(srcUri);
		request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		request.setTitle(selectedItem.getTitle());
		request.setDescription(selectedItem.getAvatar());
		setMimeType(request);
		downloadManager.enqueue(request);
	}
	
	private void setMimeType(Request request){
		request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
	}
	
	private void downloadSelected(){
		if(checkLogin()){
			accessToken = Utils.getStaticAccessToken(this);
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			List<ContentItemInfo> appIdList = new ArrayList<ContentItemInfo>();
			for(int i=0; i < adapter.getCount(); i++){
				if(adapter.getItem(i).isChecked() && checkBoxState[i] == true){
					appIdList.add(adapter.getItem(i));
				}
			}
			bgTask.buyMultipleContentCollection(accessToken, appIdList);
		} else {
			AlertDialogManager am = new AlertDialogManager(CollectionListItemActivity.this);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intent = new Intent(CollectionListItemActivity.this, LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}
	
	public void downloadAll(){
		if(checkLogin()){
			accessToken = Utils.getStaticAccessToken(this);
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			List<ContentItemInfo> appIdList = new ArrayList<ContentItemInfo>();
			for(int i=0; i < list.size(); i++){
				if(!list.get(i).isInstalled()){
					appIdList.add(list.get(i));
				}
			}
			bgTask.buyMultipleContentCollection(accessToken, appIdList);
		} else {
			AlertDialogManager am = new AlertDialogManager(CollectionListItemActivity.this);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intent = new Intent(CollectionListItemActivity.this, LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}
	
	public void onEventMainThread(BuyMultipleContentSuccessEvent event){
		accessToken = Utils.getStaticAccessToken(this);
		List<ContentItemInfo> buySuccessList = event.getBuySuccessList();
		if(buySuccessList.size() > 0){
			bgTask.getMultipleContentDownloadLink(accessToken, buySuccessList, Utils.getStaticIsRooted(this), "direct");
		}
	}
	
	public void onEventMainThread(GetMultipleDownloadLinkSucessEvent event){
		for(int i=0; i < list.size(); i++){
			checkBoxState[i] = false;
			list.get(i).setChecked(false);
		}
		count = 0;
		if(actionMode != null){
			actionMode.finish();
		}
		adapter.notifyDataSetChanged();
		if(pDialog != null){
			pDialog.dismiss();
		}
		List<DownloadLink> downloadLinkList = event.getDownloadLinkList();
		if(downloadLinkList.size() > 0){
			for(DownloadLink download : downloadLinkList){
				List<String> extraUrls = download.getExtraDownloads();
				if(extraUrls.size() > 0){
					for(String extraUrl : extraUrls){
						Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
						DownloadManager.Request request = new Request(srcUri);
						if(extraUrl.endsWith("obb")){
							String obbDir = StorageUtils.OBB_ROOT + selectedItem.getPackageName() + "/";
							File obb = new File(obbDir);
							if(!obb.exists()){
								obb.mkdirs();
							}
							request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
						} else {
							request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
						}
						request.setTitle(String.format(getResources().getString(R.string.additional_file), selectedItem.getTitle()));
						request.setDescription(selectedItem.getAvatar());
						setMimeType(request);
						downloadManager.enqueue(request);
					}
				}
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
				request.setTitle(download.getTitle());
				request.setDescription(download.getAvatar());
				setMimeType(request);
				downloadManager.enqueue(request);
			}
		}
	}
	
	private class DownloadedItemActionMode implements ActionMode.Callback {

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// TODO Auto-generated method stub
			SubMenu subMenu = menu.addSubMenu(0, R.id.action_mode_select_all, 2, "SelectAll").setIcon(R.drawable.ic_select_all);
			subMenu.add(1, R.id.menu_select_all, 0, R.string.select_all);
			subMenu.add(1, R.id.menu_de_select_all, 1, R.string.de_select_all);
			SubMenu subMenu1 = menu.addSubMenu(0, R.id.action_mode_download, 2, "Install").setIcon(R.drawable.ic_arrow_down_white);
			subMenu1.add(1, R.id.menu_download_selected, 0, R.string.download_selected);
			subMenu1.add(1, R.id.menu_download_all, 1, R.string.download_all);
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			// TODO Auto-generated method stub
			switch (item.getItemId()) {
			case R.id.menu_select_all:
				for(int i=0; i < list.size(); i++){
					checkBoxState[i] = true;
					list.get(i).setChecked(true);
				}
				count = checkBoxState.length;
				adapter.notifyDataSetChanged();
				break;
			case R.id.menu_de_select_all:
				for(int i=0; i < list.size(); i++){
					checkBoxState[i] = false;
					list.get(i).setChecked(false);
				}
				count = 0;
				actionMode.finish();
				adapter.notifyDataSetChanged();
				break;
			case R.id.menu_download_selected:
				EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.DOWNLOAD_ALL_COLLECTION, "Download selected in collection " + getIntent().getStringExtra(Constants.COLLECTION_TITLE), Long.valueOf(1));
				if(countryCode.equalsIgnoreCase("us")){
					
				} else {
					showConfirm(new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							downloadSelected();
						}
					});
				}
				break;
			case R.id.menu_download_all:
				EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.DOWNLOAD_ALL_COLLECTION, "Download all collection " + getIntent().getStringExtra(Constants.COLLECTION_TITLE), Long.valueOf(1));
				if(countryCode.equalsIgnoreCase("us")){
					
				} else {
					showConfirm(new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							for(int i=0; i < list.size(); i++){
								checkBoxState[i] = false;
								list.get(i).setChecked(false);
							}
							count = 0;
							actionMode.finish();
							adapter.notifyDataSetChanged();
							downloadAll();
						}
					});
				}
				break;
			}
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			// TODO Auto-generated method stub
			for(int i=0; i<list.size(); i++){
				checkBoxState[i] = false;
				list.get(i).setChecked(false);
			}
			count = 0;
			adapter.notifyDataSetChanged();
			actionMode = null;
		}
		
	}
	
	private void showConfirm(DialogInterface.OnClickListener l){
		AlertDialogManager am = new AlertDialogManager(this);
		am.showPositiveDialog(R.string.confirm_download_all, R.string.ok, l);
	}
}
